#!/usr/bin/env python
#
# Copyright 2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

"""Simple app to demonstrate sending two-legged OAuth requests.

Sends a signed request to http://gaeoauth.appspot.com/verify, and then
returns the response to the browser.
"""

from google.appengine.dist import use_library
use_library('django', '1.1')

import os
import sys
from google.appengine.api import urlfetch
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
import oauthfetch
import wsgiref.handlers

_UNUSED_URL = 'http://www.example.com/unused'

class FetchTwoLeggedHandler(webapp.RequestHandler):
  """Sends a request identifying the application to
  http://gaeoauth.appspot.com/verify.
  """

  def get(self):
    """Handle GET events."""
    rpc = urlfetch.create_rpc()
    oauthfetch.make_fetch_call(
        rpc,
        'http://gaeoauth.appspot.com/verify',
        oauth_request_token_url=_UNUSED_URL,
        oauth_authorization_url=_UNUSED_URL,
        oauth_access_token_url=_UNUSED_URL,
        oauth_use_token='never',
        oauth_sign_user='true',
        oauth_param_location='uri-query')
    response = oauthfetch.OAuthURLFetchResult(rpc.get_result())
    self.response.out.write(self._GetResponseHtml(response))

  def _GetResponseHtml(self, response):
    path = os.path.join(os.path.dirname(__file__), 'response.html')
    context = {
        'status_code': response.url_fetch_result.status_code,
        'oauth_error': response.oauth_error,
        'oauth_error_text': response.oauth_error_text,
        'api_response': response.url_fetch_result.content
    }
    return template.render(path, context)


# Map URLs to our RequestHandler classes above
_URLS = [
    ('/sign/twolegged', FetchTwoLeggedHandler),
]


def main(argv):
  application = webapp.WSGIApplication(_URLS, debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
  main(sys.argv)
